package com.yourcompany.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yourcompany.api.entity.UserRole;
import com.yourcompany.api.mapper.UserRoleMapper;
import com.yourcompany.api.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> 
        implements UserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignUserRoles(Long userId, List<Long> roleIds) {
        // 删除原有角色
        remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId));

        // 批量保存新角色
        if (!roleIds.isEmpty()) {
            List<UserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        userRole.setCreatorId(StpUtil.getLoginIdAsLong());
                        return userRole;
                    }).collect(Collectors.toList());
            
            saveBatch(userRoles);
        }
    }

    @Override
    public List<Long> getUserRoleIds(Long userId) {
        return baseMapper.getRoleIdsByUserId(userId);
    }

    @Override
    public List<Long> getRoleUserIds(Long roleId) {
        return baseMapper.getUserIdsByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserRoles(Long userId) {
        remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleUsers(Long roleId) {
        remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getRoleId, roleId));
    }
} 